package com.whfc.common.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;


/**
 * AES加解密工具
 *
 * @author x
 */
public class AesCryptUtil {

    private static final Logger logger = LoggerFactory.getLogger(AesCryptUtil.class);

    /**
     * AES ECB 加密
     *
     * @param message 需要加密的字符串
     * @param key     密匙
     * @return 返回加密后密文，编码为base64
     */
    public static String encryptEcb(String message, String key) {
        logger.info("AES ECB加密, message:{}, key:{}", message, key);
        final String cipherMode = "AES/ECB/PKCS5Padding";
        final String charsetName = "UTF-8";
        try {
            byte[] content;
            content = message.getBytes(charsetName);
            //
            byte[] keyByte = key.getBytes(charsetName);
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");

            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] data = cipher.doFinal(content);
            final Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(data);
        } catch (Exception e) {
            logger.warn("AES ECB加密失败", e);
        }
        return null;
    }

    /**
     * AES ECB 解密
     *
     * @param messageBase64 密文，base64编码
     * @param key           密匙，和加密时相同
     * @return 解密后数据
     */
    public static String decryptEcb(String messageBase64, String key) {
        logger.info("AES ECB解密, messageBase64:{}, key:{}", messageBase64, key);
        final String cipherMode = "AES/ECB/PKCS5Padding";
        final String charsetName = "UTF-8";
        try {
            final Base64.Decoder decoder = Base64.getDecoder();
            byte[] messageByte = decoder.decode(messageBase64);

            //
            byte[] keyByte = key.getBytes(charsetName);
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");

            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] content = cipher.doFinal(messageByte);
            return new String(content, charsetName);
        } catch (Exception e) {
            logger.warn("AES ECB解密失败", e);
        }
        return null;
    }

    public static void main(String[] args) {
        String key = "a220ba5d87dc4f11";
        String msg = "mach";
        String encrypt = AesCryptUtil.encryptEcb(msg, key);
        System.out.println(encrypt);


        String decryptStr = AesCryptUtil.decryptEcb(encrypt, key);
        System.out.println(decryptStr);
    }
}